﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using mshtml;

namespace SevenDragon
{
    public partial class jijjiang : Form
    {

        # region 成员

        System.Uri url;//当前地址
        List<Chapter> ChapterList;//章节列表
        int novelId = 0;//小说ID
        bool isMenu;//当前页面是否为目录
        bool iscomplete = false;
        string URLprefix = @"http://www.jjwxc.net/onebook.php?novelid=";
        string URLsuffix = @"&chapterid=";

        object obj;

        List<string> test = new List<string>();

        public jijjiang()
        {
            InitializeComponent();
        }

        #endregion


        /// <summary>
        /// 开始抓取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.ChapterList = new List<Chapter>();

            this.novelId = Convert.ToInt32(this.novelid.Text.Trim());//记录当前小说id
            this.url = new Uri(URLprefix+this.novelid.Text.Trim());
            
            this.webBrowser1.Url = url;//载入浏览器

            this.isMenu = true;//当前载入的是目录
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                return;
            }

            //DOM成功
            IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;

            #region 如果载入目录
            if(isMenu==true)
            {
                IHTMLElementCollection myLiks = vDocument.links;

                GetChapters(myLiks);//构建章节列表

                //todo
            }
            #endregion

            #region 如果载入内容
            if(isMenu==false)
            {
                try
                {
                    //foreach (IHTMLElement vElement in vDocument.all )
                    //{
                    //    if ((vElement.tagName.ToUpper() == "LI"))
                    //    {
                    //        //vElement.innerText = "";
                    //        test.Add(vElement.outerHTML);
                    //        //MessageBox.Show("");
                    //    }
                    //}
                    //MessageBox.Show("");
                    foreach (IHTMLElement vElement in vDocument.all)
                    {
                        if ((vElement.tagName.ToUpper() == "DIV") && (vElement.className == "rightul"))
                        {
                            this.textBox1.Text = vElement.innerText;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            #endregion
        }

        /// <summary>
        /// 获取章节列表
        /// </summary>
        /// <param name="links"></param>
        private void GetChapters(IHTMLElementCollection links)
        {
            try
            {
                foreach (HTMLAnchorElementClass el in links)
                {
                    #region old version
                    //if ((el.href.Length > this.url.ToString().Length+10) && el.href.Substring(0, this.url.ToString().Length) == this.url.ToString())
                    //{

                        //if (this.ChapterList.Contains((el.href.Replace(this.url.ToString() + "&chapterid=", ""))))
                        //{
                        //    iscomplete = true;
                        //    return;
                        //}
                        //else
                        //{
                        //    this.ChapterList.Add(el.href.Replace(this.url.ToString() + "&chapterid=", ""));
                        //}
                    //}
                    #endregion

                    //如果以http://www.jjwxc.net/onebook.php?novelid=XXXX&chapterid=开头
                    if (el.href.StartsWith(this.url.ToString() + this.URLsuffix))
                    {
                        string id=el.href.Replace(this.url.ToString(),string.Empty);
                        string name=el.innerText;
                        Chapter temp=new Chapter(id, name);

                        if (!this.ChapterList.Contains(temp))//如果没有重复的
                        {
                            this.ChapterList.Add(temp);
                        }
                        else
                        {
                            return;
                        }
                    }

                }


            }
            catch(Exception ex)
            {
                Output("构建章节列表发生错误，小说ID为" + this.novelId.ToString() + " 错误信息：" + ex.Message);
            }
        }

        private void jijjiang_Load(object sender, EventArgs e)
        {

        }



        #region 调试辅助逻辑
        private string GetDateTime()
        {
            return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        }

        private void Output(string msg)
        {
            lock (obj)
            {
                Log.WriteToFile(@"log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
            }
        }
        #endregion
    }
}
